package com.yami.shop.api.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yami.shop.bean.app.dto.NoticeDto;
import com.yami.shop.bean.enums.NoticeType;
import com.yami.shop.bean.model.Notice;
import com.yami.shop.bean.model.NotifyLog;
import com.yami.shop.bean.model.UserSearchHistory;
import com.yami.shop.common.enums.StatusEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.common.bo.UserInfoInTokenBO;
import com.yami.shop.security.common.util.AuthUserContext;
import com.yami.shop.service.NoticeService;
import com.yami.shop.service.NotifyLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import com.yami.shop.common.util.BeanUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LGH
 */
@RestController
@RequestMapping("/notice")
@Tag(name = "用户未登录状态的公告管理接口")
@AllArgsConstructor
public class NoticeController {

    private final NoticeService noticeService;
    private final NotifyLogService notifyLogService;

    @GetMapping("/topNoticeList/{shopId}")
    @Operation(summary =  "置顶公告列表信息", description = "获取所有置顶公告列表信息")
    @Parameter(name = "shopId", description = "店铺id", required = true)
    public ServerResponseEntity<List<NoticeDto>> getTopNoticeListByShopId(@PathVariable("shopId") Long shopId) {
        List<Notice> noticeList = noticeService.listTopNoticeByShopId(shopId);
        //筛选出立即发送和到时间定时发送的公告
        List<Notice> list = noticeList.stream().filter(noticeVO -> Objects.equals(noticeVO.getImmediatelySend(), 1) || (Objects.equals(noticeVO.getImmediatelySend(), 0) && noticeVO.getSendTime().before(new Date()))).collect(Collectors.toList());
        List<NoticeDto> noticeDtoList = BeanUtil.mapAsList(list, NoticeDto.class);
        UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get();
        List<NoticeDto> result;
        String accountId = "";
        //登录状态显示 指定全部用户和指定用户可见的公告
        if(Objects.nonNull(userInfoInTokenBO)){
            accountId = userInfoInTokenBO.getUserId();
            String userId = String.valueOf(accountId);
            result = noticeDtoList.stream().filter(notice ->Objects.isNull(notice.getUserIds()) || (Objects.nonNull(notice.getUserIds()) && notice.getUserIds().contains(userId) )).collect(Collectors.toList());
        }else{
            //未登录状态只显示 全部用户可见的公告
            result = noticeDtoList.stream().filter(notice -> Objects.isNull(notice.getUserIds())).collect(Collectors.toList());
        }
        return ServerResponseEntity.success(result);
    }

    @GetMapping("/info/{id}")
    @Operation(summary =  "公告详情", description = "获取公告id公告详情")
    @Parameter(name = "id", description = "公告id", required = true)
    public ServerResponseEntity<NoticeDto> getNoticeById(@PathVariable("id") Long id) {
        Notice notice = noticeService.getNoticeById(id);
        NoticeDto noticeDto = BeanUtil.map(notice, NoticeDto.class);
        return ServerResponseEntity.success(noticeDto);
    }

    /**
     * 公告列表
     */
    @GetMapping("/noticeList/{shopId}")
    @Operation(summary =  "公告列表信息", description = "获取所有公告列表信息")
    @Parameter(name = "shopId", description = "店铺id", required = true)
    public ServerResponseEntity<IPage<NoticeDto>> pageNotice(@PathVariable("shopId") Long shopId, String userId, PageParam<NoticeDto> page) {
        Notice notice = new Notice();
        notice.setShopId(shopId);
        notice.setType(NoticeType.TO_USER.value());
        notice.setAccountId(Objects.nonNull(userId) ? userId : null);
        notice.setSendTime(new Date());
        notice.setStatus(StatusEnum.ENABLE.value());
        return ServerResponseEntity.success(noticeService.pageNotice(page, notice));
    }

    /**
     * 平台发的公告列表第一条
     */
    @GetMapping("/noticeAndMassageFirst")
    @Operation(summary =  "平台发的公告列表第一条", description = "获取所有公告列表信息")
    public ServerResponseEntity<Map<String,Object>> noticeAndMassageFirst(String userId) {
        Notice notice = new Notice();
        notice.setShopId(0l);
        notice.setType(NoticeType.TO_USER.value());
        notice.setAccountId(Objects.nonNull(userId) ? userId : null);
        notice.setSendTime(new Date());
        notice.setStatus(StatusEnum.ENABLE.value());
        PageParam<NoticeDto> page = new PageParam<>();
        page.setCurrent(1);
        page.setSize(1);
        Page<NoticeDto> noticeDtoPage = noticeService.pageNotice(page, notice);
        List<NoticeDto> records = noticeDtoPage.getRecords();
        Map<String,Object> res = new HashMap<>();
        res.put("notice",records.size()>0?records.get(0):null);
        if(StrUtil.isNotEmpty(userId)){
            List<NotifyLog> notifyReminds = notifyLogService.list(Wrappers.lambdaQuery(NotifyLog.class)
                            .eq(NotifyLog::getRemindId, userId)
                            .ne(NotifyLog::getStatus, -1)
                            .lt(NotifyLog::getSendType, 51)
                            .eq(NotifyLog::getRemindType, 3)
                            .orderByAsc(NotifyLog::getStatus)
                            .orderByDesc(NotifyLog::getCreateTime).last(" limit 1 "));
            res.put("notifyLog",notifyReminds.size()>0?notifyReminds.get(0):null);
        }else{
            res.put("notifyLog",null);
        }
        return ServerResponseEntity.success(res);
    }

}
